
//
//  YZMHistoryListView.m
//  YZMicroStock
//
//  Created by apple on 16/11/15.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMHistoryListView.h"
#import "YZMStockSettlementCell.h"
#import "YZMResultView.h"
#import "YZMPageService.h"
#import "YZClient.h"
#import "YZMTradeSettlementPacket.h"
#import "YZMTradeSettlementModel.h"
#import <MJRefresh/MJRefresh.h>
#import "YZMStockViewController.h"

static NSString *const sYZMStockSettlementCellID = @"YZMStockSettlementCellID";

@interface YZMHistoryListView()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) YZMResultView *resultView;
@property (nonatomic, strong) YZMPageService *pageService;
@property (nonatomic, assign) BOOL unSuccessFetchFlag;
@property (nonatomic, assign) YZM_TRADE_TYPE tradeType;
@property(nonatomic, strong) UIImageView *noneCellImage;
@property(nonatomic, strong) UILabel *noneCellLabel;

@end

@implementation YZMHistoryListView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.backgroundColor = [YZMAppStyle appBackgroundColor];
        _dataList = [NSMutableArray array];
        _pageService = [YZMPageService new];
        self.dataSource = self;
        self.delegate = self;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self registerClass:[YZMStockSettlementCell class] forCellReuseIdentifier:sYZMStockSettlementCellID];
        self.tradeType=YZM_TRADE_TYPE_FOR_A_STOCK_D;
        self.refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchSuggestionListFirstPage)];
        self.refreshHeader.stateLabel.textColor = [YZMAppStyle colorForLightGrayText];
        self.refreshHeader.stateLabel.font = [YZMAppStyle mediumSizeFont];
        self.refreshHeader.lastUpdatedTimeLabel.hidden = YES;
        
        self.mj_header = _refreshHeader;
        
        self.refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [self fetchSuggestionListNextPage];
        }];
        [self.refreshFooter setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
        [self.refreshFooter setTitle:@"正在加载更多数据" forState:MJRefreshStateRefreshing];
        
        self.refreshFooter.stateLabel.textColor = [YZMAppStyle colorForLightGrayText];
        self.refreshFooter.stateLabel.font = [YZMAppStyle mediumSizeFont];
        
        self.mj_footer = _refreshFooter;
        
        self.resultView = [YZMResultView new];
        self.resultView.backgroundColor = [YZMAppStyle appBackgroundColor];
        [self addSubview:self.resultView];
        [self.resultView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.width.height.equalTo(self);
        }];
        
        __weak __typeof(&*self) weakSelf = self;
        self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        self.resultView.retryAction = ^(){
                [weakSelf fetchItemListForD];
        };
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:)
                                                     name:AFNetworkingReachabilityDidChangeNotification object:nil];
    }
    return self;
}


- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)reachabilityChanged:(NSNotification *)note{
    
    if (!kNetworkNotReachability) {
        
        [self fetchSuggestionListFirstPage];
    }
}

#pragma mark -- network

- (void)fetchSuggestionListFirstPage{
    
    [_pageService preChangeWithPage:_pageService.minPage andTimeEnd:YES];
        [self fetchItemListForD];
}

- (void)fetchSuggestionListNextPage{
    
    [_pageService preChangeWithPage:_pageService.nextPage  andTimeEnd:YES];
        [self fetchItemListForD];
}

- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}


-(void)fetchItemListForD
{
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [self endRefresh];
        
        if ( self.dataList.count == 0) {
            
            self.resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            self.mj_header = nil;
            self.mj_footer = nil;
            
        }else{
            
            [NSError yz_showMessageForNoWifi];
        }
        
        return;
    }
    if (!self.model) {
        
        [self endRefresh];
        return;
    }
    
    if (!YZMUserServiceInstance.isValidate) {
        
        if (self.dataList.count == 0) {
            
            self.resultView.status = YZM_RESULT_STATUS_FOR_ABNORMAL;
        }else{
            
            [NSError yz_showMessageForNoWifi];
        }
        return;
    }
    
    if (self.dataList.count == 0) {
        
        _resultView.status = YZM_RESULT_STATUS_FOR_LOADING;
    }
    
    [YZClient td_fetchTradeSettlementListForDWithPage:self.pageService.tempPage andPageSize:self.pageService.pageSize withID:self.model.Id success:^(NSURLResponse *response, id responseObject) {
        [self endRefresh];
        
        self.mj_header = _refreshHeader;
        self.mj_footer = _refreshFooter;
        self.resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        [self endRefresh];
        
        YZGeneralResultModel *topModel = responseObject;
        
        if (topModel.success) {
            [[NSNotificationCenter defaultCenter] removeObserver:self];
            
            YZMTradeSettlementPacket *result = topModel.data;
            self.unSuccessFetchFlag = YES;
            
            NSArray *sList = result.items;
            NSInteger pageIndex = result.currentPage;
            
            if (pageIndex == _pageService.minPage) {
                
                [self.dataList removeAllObjects];
                [self.dataList addObjectsFromArray:sList];
                
            }else{
                
                [self.dataList addObjectsFromArray:sList];
            }
            
            if (result.currentPage >= result.totalPage) {
                
                if (self.dataList.count == 0) {
                    
                    self.mj_footer = nil;
                }else{
                    _refreshFooter.state = MJRefreshStateNoMoreData;
                }
                
            }else{
                
                _refreshFooter.state = MJRefreshStateIdle;
            }
            [self reloadData];
            [_pageService effectChange];
        }
        else
        {
            if (self.dataList.count == 0) {
                
                [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                self.mj_header = nil;
                self.mj_footer = nil;
                
            }else{
                
                [topModel showMessage];
            }
        }
        if (_dataList.count==0) {
            [self createNoneCell];
        }
        
    } failure:^(NSError *error) {
        [self endRefresh];
        
        //网络异常处理
        if (self.dataList.count == 0) {
            
            [_resultView syncStatusWithError:error];
            self.mj_header = nil;
            self.mj_footer = nil;
            
        }else{
            
            [self endRefresh];
            [error yz_showMessage];
        }
    }];
}

-(void)createNoneCell
{
    if (!_noneCellImage) {
        _noneCellImage=[UIImageView new];
    }
    
    [_noneCellImage setImage:[UIImage imageNamed:@"icon_no_record"]];
    [self addSubview:_noneCellImage];
    [_noneCellImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(98);
        make.centerX.mas_equalTo(self);
        make.top.mas_equalTo(self).offset(155);
    }];
    
    if (!_noneCellLabel) {
        _noneCellLabel=[YZMAppStyle labelWithLargeWhite];
    }
    _noneCellLabel.text=@"暂无数据";
    [self addSubview:_noneCellLabel];
    [_noneCellLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_noneCellImage);
        make.top.mas_equalTo(_noneCellImage.mas_bottom).offset(30);
    }];
}

#pragma mark -- action

- (void)buyStockPressed {
    
    YZMStockViewController *tradeVC = nil;
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK) {
        
        tradeVC = [YZMHCMInstance instanceWithControllerName:@"stock"];
        [tradeVC showEntrustListPage];
    } else {
        
        tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
        [tradeVC showEntrustListPage];
    }
}

#pragma mark TableView DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    if (self.dataList.count == 0) {
//        
//        YZMStockSellNoneCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSellNoneCellID forIndexPath:indexPath];
//        __weak __typeof(&*self) weakSelf = self;
//        cell.addAction = ^(){
//            [weakSelf buyStockPressed];
//        };
//        return cell;
//    }
    
    YZMStockSettlementCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMStockSettlementCellID forIndexPath:indexPath];
    cell.record = self.dataList[indexPath.row];
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = self.dataList.count;
    cell.indexCount = indexCount;
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataList.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


#pragma mark -- UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.dataList.count == 0) {
        
        return self.frame.size.height - self.tableHeaderView.frame.size.height - 50;
    }
    
    return 70.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return  [UIView new];
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row >= _dataList.count) {
        return;
    }
    YZMTradeSettlementModel *instance = _dataList[indexPath.row];
    
    [YZMCMInstance pushViewControllerWithName:@"stockDetail" andParams:@{@"trade": instance,@"tradetype":@(self.tradeType)}];
}

@end